package com.wasion.pwportable.jsi;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.wasion.core.config.Config;
import com.wasion.core.db.Pagination;
import com.wasion.core.db.storage.SqliteStorage;
import com.wasion.core.db.storage.SqliteStorageListener.DataInsertListener;
import com.wasion.core.db.storage.SqliteStorageListener.DataQueryListener;
import com.wasion.core.db.storage.SqliteStorageListener.DataUpdateListener;
import com.wasion.core.db.storage.StorageQuery;
import com.wasion.core.db.storage.StorageQuery.SortOrder;
import com.wasion.core.util.DateTimeUtil;
import com.wasion.core.util.StringUtil;
import com.wasion.pwportable.activity.PwPortableActivity;
import com.wasion.pwportable.dao.sd.IndicatorSDDBDao;
import com.wasion.pwportable.dao.sd.IndicatorStatusSDDBDao;
import com.wasion.pwportable.dao.sd.TerminalSDDBDao;
import com.wasion.pwportable.dao.sd.WorkLineSDDBDao;
import com.wasion.pwportable.domain.po.Indicator;
import com.wasion.pwportable.domain.po.Terminal;

/**
 * 
 * @ClassName: IndicatorJSI
 * @Description: 指示器JavaScriptInterface，对指示器操作交互接口<br/>
 *               1. 增加/修改指示器 <br/>
 *               2. 删除指示器 <br/>
 *               3. 获取指示器 <br/>
 * @author 高意
 * @date 2014-8-1 下午2:57:06
 * 
 */
public class IndicatorJSI {

	// 应用上下文
	private Context context;

	// webview，浏览器窗口
	private WebView webView;

	// Sqlite存储实例
	private SqliteStorage sqliteStorage = null;

	// Google的Json转换工具
	private Gson gson = new Gson();

	// 指示器数据库访问接口
	private IndicatorSDDBDao indicatorSDDBDao = null;

	// 提示语
	private String tip = "";

	// 返回结果
	Map<String, Object> resultMap = new HashMap<String, Object>();

	// 指示器组集合
	List<Indicator> indicators = new ArrayList<Indicator>();

	// 指示器
	Indicator indicator = new Indicator();

	// Excel sheet
	private WritableSheet sheet;

	private WritableWorkbook workBook;

	// 是否点击查询按钮触发事件
	private boolean isQuery;

	public IndicatorJSI(Context context) {
		this.context = context;
		this.webView = PwPortableActivity.getWebView();
		this.sqliteStorage = SqliteStorage.getInstance(this.context);
		indicatorSDDBDao = new IndicatorSDDBDao(context);
	}

	/**
	 * 
	 * @Title: addOrModifyIGroup
	 * @Description: 新增/修改指示器组
	 * @param
	 * @return
	 * @throws
	 */
	public void addOrModifyIGroup(final String jsonStr) {

		JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
		int groupno = json.get("groupNo").getAsInt();
		String location = json.get("location").getAsString();
		String lineid = json.get("lineId").getAsString();
		String terminalid = json.get("terminalId").getAsString();
		final String operMode = json.get("operMode").getAsString();
		String time = DateTimeUtil.getCurrentDate();

		indicators.clear();

		String indicatorAddrA = json.get("indicatorAddrA").getAsString();
		if (!StringUtil.isEmpty(indicatorAddrA)) {

			Indicator ia = new Indicator();
			ia.setGroupno(groupno);
			ia.setLocation(location);
			ia.setLineid(lineid);
			ia.setTerminalid(terminalid);
			ia.setIndicatoraddr(indicatorAddrA);
			ia.setTime(time);
			ia.setPhase("1");
			indicators.add(ia);
		}

		String indicatorAddrB = json.get("indicatorAddrB").getAsString();
		if (!StringUtil.isEmpty(indicatorAddrB)) {

			Indicator ib = new Indicator();
			ib.setGroupno(groupno);
			ib.setLocation(location);
			ib.setLineid(lineid);
			ib.setTerminalid(terminalid);
			ib.setIndicatoraddr(indicatorAddrB);
			ib.setTime(time);
			ib.setPhase("2");
			indicators.add(ib);
		}

		String indicatorAddrC = json.get("indicatorAddrC").getAsString();
		if (!StringUtil.isEmpty(indicatorAddrC)) {

			Indicator ic = new Indicator();
			ic.setGroupno(groupno);
			ic.setLocation(location);
			ic.setLineid(lineid);
			ic.setTerminalid(terminalid);
			ic.setIndicatoraddr(indicatorAddrC);
			ic.setTime(time);
			ic.setPhase("3");
			indicators.add(ic);
		}

		if ("add".equalsIgnoreCase(operMode)) {
			tip = "添加";
		} else {
			tip = "修改";
		}

		// 1. 删除终端、组号下的所有指示器
		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("groupno", groupno);
		storageQuery.equals("terminalid", terminalid);

		sqliteStorage.deleteData(storageQuery, indicatorSDDBDao,
				new DataUpdateListener() {

					public void onSuccess(long paramLong) {
						// 2. 添加指示器组
						sqliteStorage.insertData(indicators, indicatorSDDBDao,
								new DataInsertListener() {

									public void onSuccess(long paramLong) {
										JSIHelper.showToast(context, tip
												+ "成功!");

										resultMap.clear();
										resultMap.put("success", true);
										resultMap.put("operMode", operMode);
										String result = gson.toJson(resultMap);

										webView.loadUrl("javascript:igroupAMSuccuessCallback("
												+ result + ")");
									}

									public void onFailure(int errorCode,
											String errorMessage) {
										JSIHelper.showToast(context, tip
												+ "失败!");
									}
								});
					}

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, tip + "失败!");
					}
				});
	}

	/**
	 * 
	 * @Title: addIGroup
	 * @Description: 新增指示器组
	 * @param
	 * @return
	 * @throws
	 */
	public void addIGroup(final String jsonStr) {
		PwPortableActivity.getHandler().post(new Runnable() {
			public void run() {
				JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
				int groupno = json.get("groupNo").getAsInt();
				String location = json.get("location").getAsString();
				String lineid = json.get("lineId").getAsString();
				String terminalid = json.get("terminalId").getAsString();
				final String operMode = json.get("operMode").getAsString();
				String time = DateTimeUtil.getCurrentDate();

				indicators.clear();

				String indicatorAddrA = json.get("indicatorAddrA")
						.getAsString();
				String indicatorAddrB = json.get("indicatorAddrB")
						.getAsString();
				String indicatorAddrC = json.get("indicatorAddrC")
						.getAsString();

				// 判断当前录入的指示器地址是否重复
				int num = 0;
				StringBuilder indicatorAddrs = new StringBuilder();
				Set<String> addrSet = new LinkedHashSet<String>();
				StringBuilder repeatIAddrs = new StringBuilder();
				if (!StringUtil.isEmpty(indicatorAddrA)) {
					indicatorAddrA = indicatorAddrA.toUpperCase();
					if (!addrSet.contains(indicatorAddrA)) {
						indicatorAddrs.append("'").append(indicatorAddrA)
								.append("',");
					} else {
						repeatIAddrs.append("'").append(indicatorAddrA)
								.append("',");
					}
					addrSet.add(indicatorAddrA);
					num++;
				}
				if (!StringUtil.isEmpty(indicatorAddrB)) {
					indicatorAddrB = indicatorAddrB.toUpperCase();
					if (!addrSet.contains(indicatorAddrB)) {
						indicatorAddrs.append("'").append(indicatorAddrB)
								.append("',");
					} else {
						repeatIAddrs.append("'").append(indicatorAddrB)
								.append("',");
					}
					addrSet.add(indicatorAddrB);
					num++;
				}
				if (!StringUtil.isEmpty(indicatorAddrC)) {
					indicatorAddrC = indicatorAddrC.toUpperCase();
					if (!addrSet.contains(indicatorAddrC)) {
						indicatorAddrs.append("'").append(indicatorAddrC)
								.append("',");
					} else {
						repeatIAddrs.append("'").append(indicatorAddrC)
								.append("',");
					}
					addrSet.add(indicatorAddrC);
					num++;
				}

				IndicatorSDDBDao indicatorSDDBDao = new IndicatorSDDBDao(
						context);
				indicatorSDDBDao.startReadableDatabase(false);
				String temp = indicatorAddrs.toString().substring(0,
						indicatorAddrs.length() - 1);
				List<Indicator> list = indicatorSDDBDao.queryList(
						"indicatoraddr in (" + temp.toUpperCase() + ")",
						new String[] {});
				indicatorSDDBDao.closeDatabase(false);

				if (num != addrSet.size() || 0 < list.size()) {
					for (Indicator indicator : list) {
						repeatIAddrs.append("'")
								.append(indicator.getIndicatoraddr())
								.append("',");
					}
					resultMap.clear();
					resultMap.put("success", false);
					resultMap.put("flag", 1);
					resultMap.put("operMode", operMode);
					resultMap.put("repeatIAddrs", repeatIAddrs.substring(0,
							repeatIAddrs.length() - 1));
					String result = gson.toJson(resultMap);

					webView.loadUrl("javascript:igroupAMSuccuessCallback("
							+ result + ")");
					return;
				}

				// 1. 查询最大的测量点号
				int maxMeasurepoint = getMaxMeasurepoint(terminalid);

				if (!StringUtil.isEmpty(indicatorAddrA)) {

					maxMeasurepoint++;

					Indicator ia = new Indicator();
					ia.setGroupno(groupno);
					ia.setLocation(location);
					ia.setLineid(lineid);
					ia.setTerminalid(terminalid);
					ia.setIndicatoraddr(indicatorAddrA.toUpperCase());
					ia.setTime(time);
					ia.setPhase("1");
					ia.setMeasurepoint(maxMeasurepoint);
					indicators.add(ia);
				}

				if (!StringUtil.isEmpty(indicatorAddrB)) {

					maxMeasurepoint++;

					Indicator ib = new Indicator();
					ib.setGroupno(groupno);
					ib.setLocation(location);
					ib.setLineid(lineid);
					ib.setTerminalid(terminalid);
					ib.setIndicatoraddr(indicatorAddrB.toUpperCase());
					ib.setTime(time);
					ib.setPhase("2");
					ib.setMeasurepoint(maxMeasurepoint);
					indicators.add(ib);
				}

				if (!StringUtil.isEmpty(indicatorAddrC)) {

					maxMeasurepoint++;

					Indicator ic = new Indicator();
					ic.setGroupno(groupno);
					ic.setLocation(location);
					ic.setLineid(lineid);
					ic.setTerminalid(terminalid);
					ic.setIndicatoraddr(indicatorAddrC.toUpperCase());
					ic.setTime(time);
					ic.setPhase("3");
					ic.setMeasurepoint(maxMeasurepoint);
					indicators.add(ic);
				}

				tip = "添加";

				// 2. 添加指示器组
				sqliteStorage.insertData(indicators, indicatorSDDBDao,
						new DataInsertListener() {

							public void onSuccess(long paramLong) {
								JSIHelper.showToast(context, tip + "成功!");

								resultMap.clear();
								resultMap.put("success", true);
								resultMap.put("operMode", operMode);
								String result = gson.toJson(resultMap);

								webView.loadUrl("javascript:igroupAMSuccuessCallback("
										+ result + ")");
							}

							public void onFailure(int errorCode,
									String errorMessage) {
								JSIHelper.showToast(context, tip + "失败!");

								resultMap.clear();
								resultMap.put("success", false);
								resultMap.put("flag", 2);
								resultMap.put("operMode", operMode);
								String result = gson.toJson(resultMap);

								webView.loadUrl("javascript:igroupAMSuccuessCallback("
										+ result + ")");
							}
						});
			}
		});
	}

	/**
	 * 
	 * @Title: modifyIGroup
	 * @Description: 修改指示器组
	 * @param
	 * @return
	 * @throws
	 */
	public void modifyIGroup(final String jsonStr) {
		PwPortableActivity.getHandler().post(new Runnable() {
			public void run() {
				tip = "修改";
				try {
					JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
					int groupno = json.get("groupNo").getAsInt();
					String location = json.get("location").getAsString();
					String lineid = json.get("lineId").getAsString();
					String terminalid = json.get("terminalId").getAsString();
					final String operMode = json.get("operMode").getAsString();
					String time = DateTimeUtil.getCurrentDate();

					String indicatorIdA = json.get("indicatorIdA")
							.getAsString();
					String indicatorAddrA = json.get("indicatorAddrA")
							.getAsString();
					String indicatorIdB = json.get("indicatorIdB")
							.getAsString();
					String indicatorAddrB = json.get("indicatorAddrB")
							.getAsString();
					String indicatorIdC = json.get("indicatorIdC")
							.getAsString();
					String indicatorAddrC = json.get("indicatorAddrC")
							.getAsString();

					// 判断当前录入的指示器地址是否重复
					int num = 0;
					StringBuilder indicatorAddrs = new StringBuilder();
					StringBuilder indicatorIds = new StringBuilder();
					StringBuilder repeatIAddrs = new StringBuilder();
					Set<String> addrSet = new LinkedHashSet<String>();
					if (!StringUtil.isEmpty(indicatorAddrA)) {
						indicatorAddrA = indicatorAddrA.toUpperCase();
						if (!addrSet.contains(indicatorAddrA)) {
							indicatorAddrs.append("'").append(indicatorAddrA)
									.append("',");
						} else {
							repeatIAddrs.append("'").append(indicatorAddrA)
									.append("',");
						}
						addrSet.add(indicatorAddrA);
						num++;
					}
					if (!StringUtil.isEmpty(indicatorAddrB)) {
						indicatorAddrB = indicatorAddrB.toUpperCase();
						if (!addrSet.contains(indicatorAddrB)) {
							indicatorAddrs.append("'").append(indicatorAddrB)
									.append("',");
						} else {
							repeatIAddrs.append("'").append(indicatorAddrB)
									.append("',");
						}
						addrSet.add(indicatorAddrB);
						num++;
					}
					if (!StringUtil.isEmpty(indicatorAddrC)) {
						indicatorAddrC = indicatorAddrC.toUpperCase();
						if (!addrSet.contains(indicatorAddrC)) {
							indicatorAddrs.append("'").append(indicatorAddrC)
									.append("',");
						} else {
							repeatIAddrs.append("'").append(indicatorAddrC)
									.append("',");
						}
						addrSet.add(indicatorAddrC);
						num++;
					}

					if (!StringUtil.isEmpty(indicatorIdA)) {
						indicatorIds.append("'").append(indicatorIdA)
								.append("',");
					}
					if (!StringUtil.isEmpty(indicatorIdB)) {
						indicatorIds.append("'").append(indicatorIdB)
								.append("',");
					}
					if (!StringUtil.isEmpty(indicatorIdC)) {
						indicatorIds.append("'").append(indicatorIdC)
								.append("',");
					}

					IndicatorSDDBDao indicatorSDDBDao = new IndicatorSDDBDao(
							context);
					indicatorSDDBDao.startReadableDatabase(false);
					String tempAddrs = indicatorAddrs.toString().substring(0,
							indicatorAddrs.length() - 1);
					String tempIds = indicatorIds.toString().substring(0,
							indicatorIds.length() - 1);
					List<Indicator> list = indicatorSDDBDao.queryList(
							"indicatoraddr in (" + tempAddrs.toUpperCase()
									+ ") and _id not in (" + tempIds + ")",
							new String[] {});
					indicatorSDDBDao.closeDatabase(false);

					if (num != addrSet.size() || 0 < list.size()) {
						for (Indicator indicator : list) {
							repeatIAddrs.append("'")
									.append(indicator.getIndicatoraddr())
									.append("',");
						}

						resultMap.clear();
						resultMap.put("success", false);
						resultMap.put("flag", 1);
						resultMap.put("operMode", operMode);
						resultMap.put("repeatIAddrs", repeatIAddrs.substring(0,
								repeatIAddrs.length() - 1));
						String result = gson.toJson(resultMap);

						webView.loadUrl("javascript:igroupAMSuccuessCallback("
								+ result + ")");
						return;
					}

					int maxMeasurepoint = getMaxMeasurepoint(terminalid);

					indicatorSDDBDao.startReadableDatabase(false);

					if (StringUtil.isEmpty(indicatorIdA)) {

						if (!StringUtil.isEmpty(indicatorAddrA)) {

							maxMeasurepoint++;

							Indicator i = new Indicator();
							i.setGroupno(groupno);
							i.setLocation(location);
							i.setLineid(lineid);
							i.setTerminalid(terminalid);
							i.setIndicatoraddr(indicatorAddrA.toUpperCase());
							i.setTime(time);
							i.setPhase("1");
							i.setMeasurepoint(maxMeasurepoint);

							indicatorSDDBDao.insert(i);
						}
					} else {
						if (StringUtil.isEmpty(indicatorAddrA)) {
							IndicatorStatusSDDBDao indicatorStatusSDDBDao = new IndicatorStatusSDDBDao(
									context);
							indicatorStatusSDDBDao.startReadableDatabase(false);
							indicatorStatusSDDBDao.execSql(
									"delete from indicator_status where _id=?",
									new String[] { indicatorIdA });
							indicatorStatusSDDBDao.closeDatabase(false);

							indicatorSDDBDao.delete(Integer
									.parseInt(indicatorIdA));
						} else {
							indicatorSDDBDao
									.execSql(
											"update indicator set location=?,indicatoraddr=?,time=? where _id=?",
											new String[] {
													location,
													indicatorAddrA
															.toUpperCase(),
													time, indicatorIdA });
						}
					}

					if (StringUtil.isEmpty(indicatorIdB)) {

						if (!StringUtil.isEmpty(indicatorAddrB)) {

							maxMeasurepoint++;

							Indicator i = new Indicator();
							i.setGroupno(groupno);
							i.setLocation(location);
							i.setLineid(lineid);
							i.setTerminalid(terminalid);
							i.setIndicatoraddr(indicatorAddrB.toUpperCase());
							i.setTime(time);
							i.setPhase("2");
							i.setMeasurepoint(maxMeasurepoint);

							indicatorSDDBDao.insert(i);
						}
					} else {
						if (StringUtil.isEmpty(indicatorAddrB)) {

							IndicatorStatusSDDBDao indicatorStatusSDDBDao = new IndicatorStatusSDDBDao(
									context);
							indicatorStatusSDDBDao.startReadableDatabase(false);
							indicatorStatusSDDBDao.execSql(
									"delete from indicator_status where _id=?",
									new String[] { indicatorIdB });
							indicatorStatusSDDBDao.closeDatabase(false);

							indicatorSDDBDao.delete(Integer
									.parseInt(indicatorIdB));
						} else {
							indicatorSDDBDao
									.execSql(
											"update indicator set location=?,indicatoraddr=?,time=? where _id=?",
											new String[] {
													location,
													indicatorAddrB
															.toUpperCase(),
													time, indicatorIdB });
						}
					}

					if (StringUtil.isEmpty(indicatorIdC)) {

						if (!StringUtil.isEmpty(indicatorAddrC)) {

							maxMeasurepoint++;

							Indicator i = new Indicator();
							i.setGroupno(groupno);
							i.setLocation(location);
							i.setLineid(lineid);
							i.setTerminalid(terminalid);
							i.setIndicatoraddr(indicatorAddrC.toUpperCase());
							i.setTime(time);
							i.setPhase("3");
							i.setMeasurepoint(maxMeasurepoint);

							indicatorSDDBDao.insert(i);
						}
					} else {
						if (StringUtil.isEmpty(indicatorAddrC)) {
							IndicatorStatusSDDBDao indicatorStatusSDDBDao = new IndicatorStatusSDDBDao(
									context);
							indicatorStatusSDDBDao.startReadableDatabase(false);
							indicatorStatusSDDBDao.execSql(
									"delete from indicator_status where _id=?",
									new String[] { indicatorIdC });
							indicatorStatusSDDBDao.closeDatabase(false);

							indicatorSDDBDao.delete(Integer
									.parseInt(indicatorIdC));
						} else {
							indicatorSDDBDao
									.execSql(
											"update indicator set location=?,indicatoraddr=?,time=? where _id=?",
											new String[] {
													location,
													indicatorAddrC
															.toUpperCase(),
													time, indicatorIdC });

						}
					}

					indicatorSDDBDao.closeDatabase(false);

					JSIHelper.showToast(context, tip + "成功!");

					resultMap.clear();
					resultMap.put("success", true);
					resultMap.put("operMode", operMode);
					String result = gson.toJson(resultMap);

					webView.loadUrl("javascript:igroupAMSuccuessCallback("
							+ result + ")");
				} catch (Exception e) {
					JSIHelper.showToast(context, tip + "失败!");
				}
			}
		});
	}

	/**
	 * 
	 * @Title: getMaxMeasurepoint
	 * @Description: 获取最大的测量点号
	 * @param
	 * @return
	 * @throws
	 */
	protected int getMaxMeasurepoint(String terminalId) {

		indicatorSDDBDao.startReadableDatabase(false);
		List<Map<String, String>> maps = indicatorSDDBDao
				.queryMapList(
						"select distinct max(measurepoint) as maxmeasurepoint from indicator where terminalid=?",
						new String[] { terminalId });
		indicatorSDDBDao.closeDatabase(false);

		String maxMeasurepointStr = maps.get(0).get("maxmeasurepoint");
		int maxMeasurepoint = 0;
		if (!StringUtil.isEmpty(maxMeasurepointStr)) {
			maxMeasurepoint = Integer.parseInt(maxMeasurepointStr);
		}

		return maxMeasurepoint;
	}

	/**
	 * 
	 * @Title: removeIGroup
	 * @Description: 删除指示器组
	 * @param
	 * @return
	 * @throws
	 */
	public void removeIGroup(final String terminalid, final String groupno) {

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("terminalid", terminalid);
		storageQuery.equals("groupno", Integer.parseInt(groupno));

		sqliteStorage.findData(storageQuery, indicatorSDDBDao,
				new DataQueryListener() {

					@SuppressWarnings("unchecked")
					@Override
					public void onSuccess(List<?> paramList) {
						List<Indicator> indicators = (List<Indicator>) paramList;
						for (Indicator i : indicators) {
							int indicatorId = i.get_id();
							IndicatorStatusSDDBDao indicatorStatusSDDBDao = new IndicatorStatusSDDBDao(
									context);
							indicatorStatusSDDBDao.startReadableDatabase(false);
							indicatorStatusSDDBDao.execSql(
									"delete from indicator_status where _id=?",
									new String[] { indicatorId + "" });
							indicatorStatusSDDBDao.closeDatabase(false);
						}

						StorageQuery storageQuery = new StorageQuery();
						storageQuery.equals("terminalid", terminalid);
						storageQuery.equals("groupno",
								Integer.parseInt(groupno));

						sqliteStorage.deleteData(storageQuery,
								indicatorSDDBDao, new DataUpdateListener() {

									public void onSuccess(long paramLong) {
										JSIHelper.showToast(context, "删除成功!");

										resultMap.clear();
										resultMap.put("success", true);
										resultMap.put("groupno", groupno);

										String jsonStr = gson.toJson(resultMap);
										webView.loadUrl("javascript:removeIGroupCallback("
												+ jsonStr + ")");
									}

									public void onFailure(int errorCode,
											String errorMessage) {
										JSIHelper.showToast(context, "删除失败!");
									}
								});
					}

					@Override
					public void onFailure(int errorCode, String errorMessage) {
					}
				});

	}

	/**
	 * 
	 * @Title: queryIGroup
	 * @Description: 获取指示器组
	 * @param
	 * @return
	 * @throws
	 */
	public void queryIGroup(final String jsonStr) {

		Indicator indicator = new Indicator();
		indicator = gson.fromJson(jsonStr, Indicator.class);

		StorageQuery storageQuery = new StorageQuery();

		int groupno = indicator.getGroupno();
		if (0 != groupno) {
			storageQuery.equals("groupno", groupno);
		}

		String terminalid = indicator.getTerminalid();
		if (!StringUtil.isEmpty(terminalid)) {
			storageQuery.equals("terminalid", terminalid);
		}

		sqliteStorage.findData(storageQuery, indicatorSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询指示器失败!");
					}

					@SuppressWarnings("unchecked")
					public void onSuccess(List<?> paramList) {

						resultMap.clear();
						resultMap.put("success", true);
						if (null != paramList && 0 < paramList.size()) {
							try {
								for (Indicator i : (List<Indicator>) paramList) {
									if ("1".equals(i.getPhase())) {
										resultMap.put("indicatorAddrA",
												i.getIndicatoraddr());
										resultMap.put("indicatorIdA",
												i.get_id());
										resultMap.put("groupno", i.getGroupno());
										resultMap.put("location",
												i.getLocation());
										continue;
									}

									if ("2".equals(i.getPhase())) {
										resultMap.put("indicatorAddrB",
												i.getIndicatoraddr());
										resultMap.put("indicatorIdB",
												i.get_id());
										resultMap.put("groupno", i.getGroupno());
										resultMap.put("location",
												i.getLocation());
										continue;
									}

									if ("3".equals(i.getPhase())) {
										resultMap.put("indicatorAddrC",
												i.getIndicatoraddr());
										resultMap.put("indicatorIdC",
												i.get_id());
										resultMap.put("groupno", i.getGroupno());
										resultMap.put("location",
												i.getLocation());
										continue;
									}
								}

								String jsonStr = gson.toJson(resultMap);

								webView.loadUrl("javascript:queryIGroupCallback("
										+ jsonStr + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						}
					}
				});
	}

	/**
	 * 
	 * @Title: queryIndicators
	 * @Description: 获取指示器
	 * @param
	 * @return
	 * @throws
	 */
	public void queryIndicators(final String jsonStr) {

		Indicator indicator = new Indicator();
		indicator = gson.fromJson(jsonStr, Indicator.class);

		StorageQuery storageQuery = new StorageQuery();
		if (null != indicator) {
			int _id = indicator.get_id();
			if (0 != _id) {
				storageQuery.equals("_id", _id);
			}

			int groupno = indicator.getGroupno();
			if (0 != groupno) {
				storageQuery.equals("groupno", groupno);
			}

			String terminalid = indicator.getTerminalid();
			if (!StringUtil.isEmpty(terminalid)) {
				storageQuery.equals("terminalid", terminalid);
			}
		}

		storageQuery.addSort("time", SortOrder.DESC);

		sqliteStorage.findData(storageQuery, indicatorSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询指示器失败!");
					}

					public void onSuccess(List<?> paramList) {

						// if (null != paramList && 0 < paramList.size()) {
						try {
							String jsonStr = gson.toJson(paramList);

							webView.loadUrl("javascript:loadIndicators("
									+ jsonStr + ")");
						} catch (Exception e) {
							JSIHelper.showToast(context, e.getMessage());
						}
						// }
					}
				});
	}

	/**
	 * 
	 * @Title: parsePhasetext
	 * @Description: 相位转换为名称
	 * @param
	 * @return
	 * @throws
	 */
	protected String parsePhasetext(String phase) {

		String phaseText = "";
		if ("1".equals(phase)) {
			phaseText = "A相";
		} else if ("2".equals(phase)) {
			phaseText = "B相";
		} else if ("3".equals(phase)) {
			phaseText = "C相";
		}

		return phaseText;
	}

	/**
	 * 
	 * @Title: queryIndicatorsByPage
	 * @Description: 分页获取指示器
	 * @param
	 * @return
	 * @throws
	 */
	public void queryIndicatorsByPage(final String jsonStr) {

		StorageQuery storageQuery = new StorageQuery();
		try {
			JSONObject jsObj = new JSONObject(jsonStr);
			isQuery = jsObj.getBoolean("isQuery");

			if (!jsObj.isNull("pId")) {
				storageQuery.equals("terminalid", jsObj.getString("pId"));
			}
			if (!jsObj.isNull("indicatoraddr")) {
				storageQuery.like("upper(indicatoraddr)",
						jsObj.getString("indicatoraddr").toUpperCase());
			}

			int size = Pagination.DEFAULT_PAGE_SIZE;
			if (!jsObj.isNull("pagesize")) {
				storageQuery.setLimit(Integer.parseInt(jsObj
						.getString("pagesize")));
			} else {
				storageQuery.setLimit(Pagination.DEFAULT_PAGE_SIZE);
			}

			if (!jsObj.isNull("page")) {
				storageQuery.setOffset(size
						* (Integer.parseInt(jsObj.getString("page")) - 1));
			} else {
				storageQuery.setOffset(size * (Pagination.DEFAULT_PAGE - 1));
			}

			storageQuery.addSort("terminalid,groupno,phase", SortOrder.ASC);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		sqliteStorage.findData(storageQuery, indicatorSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询指示器失败!");
					}

					@SuppressWarnings("unchecked")
					public void onSuccess(List<?> paramList) {

						if (isQuery
								&& (null == paramList || 0 == paramList.size())) {
							String jsonStr = gson.toJson(paramList);

							webView.loadUrl("javascript:queryIndicatorsByPageCallback("
									+ jsonStr + ")");
							return;
						}

						if (null != paramList && 0 < paramList.size()) {

							for (Indicator i : (List<Indicator>) paramList) {
								String phase = i.getPhase();
								i.setPhasetext(parsePhasetext(phase));
								String terminalId = i.getTerminalid();

								TerminalSDDBDao terminalSDDBDao = new TerminalSDDBDao(
										context);
								terminalSDDBDao.startReadableDatabase(false);
								List<Terminal> terminals = terminalSDDBDao
										.queryList(
												new String[] { "terminaladdr", },
												"_id=?",
												new String[] { terminalId + "" },
												null, null, null, null);
								terminalSDDBDao.closeDatabase(false);

								if (0 != terminals.size()) {
									i.setTerminaladdr(terminals.get(0)
											.getTerminaladdr());
								}
							}

							try {
								String jsonStr = gson.toJson(paramList);

								webView.loadUrl("javascript:queryIndicatorsByPageCallback("
										+ jsonStr + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						} else {
							JSIHelper.showToast(context, "已加载所有指示器!");
						}
					}
				});
	}

	/**
	 * 
	 * @Title: exportIndicators
	 * @Description: 导出指示器信息
	 * @param
	 * @return
	 * @throws
	 */
	public void exportIndicators(String jsonStr) {

		StorageQuery storageQuery = new StorageQuery();
		try {
			JSONObject jsObj = new JSONObject(jsonStr);

			if (!jsObj.isNull("indicatoraddr")) {
				storageQuery.like("upper(indicatoraddr)",
						jsObj.getString("indicatoraddr").toUpperCase());
			}

			storageQuery.addSort("terminalid,groupno,branch", SortOrder.ASC);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		sqliteStorage.findData(storageQuery, indicatorSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询指示器失败!");
					}

					public void onSuccess(List<?> paramList) {

						try {
							String path = "";
							String fileName = DateTimeUtil
									.getCurrentDate("yyyyMMddHHmmss") + ".xls";

							File usbDirectory = new File(Export.getUDiskPath());
							if (usbDirectory.exists()
									&& usbDirectory.isDirectory()
									&& usbDirectory.canWrite()) {
								path = Export.getUDiskPath() + "/"
										+ Config.EXPORT_PATH + "/indicator/";
							} else {
								path = Export.getSDPath() + "/"
										+ Config.EXPORT_PATH + "/indicator/";
							}

							File directory = new File(path);
							if (!directory.exists() && !directory.isDirectory()) {
								directory.mkdirs();
							}

							File file = new File(path + fileName);
							if (!file.exists()) {
								file.createNewFile();
							}

							// 创建一个可写入的工作薄(Workbook)对象
							workBook = Workbook.createWorkbook(file);

							if (workBook != null) {
								// 第一个参数是工作表的名称，第二个是工作表在工作薄中的位置
								sheet = workBook.createSheet("指示器", 0);

								// 设置表名和表头的行高
								sheet.setRowView(0, 800);
								sheet.setRowView(1, 600);

								// 设置列宽
								sheet.setColumnView(0, 10);
								sheet.setColumnView(1, 18);
								sheet.setColumnView(2, 18);
								sheet.setColumnView(3, 30);
								sheet.setColumnView(4, 15);
								sheet.setColumnView(5, 10);
								sheet.setColumnView(6, 25);

								// 合并单元格，在指定单元格插入表名
								sheet.mergeCells(0, 0, 6, 0);
								sheet.addCell(new Label(0, 0, "指示器信息表", Export
										.getTitleCellFormat()));

								// 在指定单元格插入表头
								sheet.addCell(new Label(0, 1, "序号", Export
										.getHeaderCellFormat()));
								sheet.addCell(new Label(1, 1, "指示器地址", Export
										.getHeaderCellFormat()));
								sheet.addCell(new Label(2, 1, "终端地址", Export
										.getHeaderCellFormat()));
								sheet.addCell(new Label(3, 1, "安装位置", Export
										.getHeaderCellFormat()));
								sheet.addCell(new Label(4, 1, "相位", Export
										.getHeaderCellFormat()));
								sheet.addCell(new Label(5, 1, "分支路径", Export
										.getHeaderCellFormat()));
								sheet.addCell(new Label(6, 1, "时间", Export
										.getHeaderCellFormat()));
								if (null != paramList && 0 < paramList.size()) {

									// 在接下来的内容中插入数据
									for (int i = 0; i < paramList.size(); i++) {
										Indicator indicator = (Indicator) paramList
												.get(i);

										String phase = indicator.getPhase();
										indicator
												.setPhasetext(parsePhasetext(phase));
										String terminalId = indicator
												.getTerminalid();

										TerminalSDDBDao terminalSDDBDao = new TerminalSDDBDao(
												context);
										terminalSDDBDao
												.startReadableDatabase(false);
										List<Terminal> terminals = terminalSDDBDao
												.queryList(
														new String[] { "terminaladdr" },
														"_id=?",
														new String[] { terminalId
																+ "" }, null,
														null, null, null);
										terminalSDDBDao.closeDatabase(false);

										if (0 < terminals.size()) {
											indicator.setTerminaladdr(terminals
													.get(0).getTerminaladdr());
										}

										int row = 2 + i;
										try {

											String branchLevel = null != indicator
													.getBranch() ? ((int) Math.ceil(Integer
													.parseInt(indicator
															.getBranch()) / 3.0)
													+ " - " + indicator
													.getLevel())
													: "";
											sheet.addCell(new Label(0, row,
													indicator.get_id() + "",
													Export.getBodyCellFormat()));
											sheet.addCell(new Label(
													1,
													row,
													indicator
															.getIndicatoraddr(),
													Export.getBodyCellFormat()));
											sheet.addCell(new Label(
													2,
													row,
													indicator.getTerminaladdr(),
													Export.getBodyCellFormat()));
											sheet.addCell(new Label(3, row,
													indicator.getLocation(),
													Export.getBodyCellFormat()));
											sheet.addCell(new Label(4, row,
													indicator.getPhasetext(),
													Export.getBodyCellFormat()));
											sheet.addCell(new Label(5, row,
													branchLevel,
													Export.getBodyCellFormat()));
											sheet.addCell(new Label(6, row,
													indicator.getTime(),
													Export.getBodyCellFormat()));
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}

								// 从内存中写入文件中
								workBook.write();
								workBook.close();

								JSIHelper.showToast(context, "指示器导出成功!");
							}
						} catch (Exception e) {
							e.printStackTrace();
							JSIHelper.showToast(context, "导出指示器发生异常!");
						}
					}
				});
	}

	/**
	 * 
	 * @Title: getMaxGroupNo
	 * @Description: 获取组号的最大值
	 * @param
	 * @return
	 * @throws
	 */
	public void getMaxGroupNo(final String lineId, final String x,
			final String y) {

		PwPortableActivity.getHandler().post(new Runnable() {
			public void run() {

				indicatorSDDBDao.startReadableDatabase(false);
				List<Map<String, String>> maps = indicatorSDDBDao
						.queryMapList(
								"select distinct max(groupno) as maxgroupno from indicator where lineid=?",
								new String[] { lineId });
				indicatorSDDBDao.closeDatabase(false);

				if (null != maps && 0 < maps.size()) {
					try {
						String maxGroupNo = maps.get(0).get("maxgroupno");
						if (null == maxGroupNo) {
							maxGroupNo = "0";
						}
						String result = "{maxGroupNo: '"
								+ Integer.parseInt(maxGroupNo) + "', x: '" + x
								+ "', y: '" + y + "'}";

						webView.loadUrl("javascript:readyIgroupCallback("
								+ result + ")");
					} catch (Exception e) {
						JSIHelper.showToast(context, e.getMessage());
					}
				} else {
					String result = "{maxGroupNo: '0', x: '" + x + "', y: '"
							+ y + "'}";

					webView.loadUrl("javascript:loadTerminals(" + result + ")");
				}
			}
		});
	}

	/**
	 * 
	 * @Title: setBranchLevel
	 * @Description: 设置各指示器的分支号和分支级数
	 * @param
	 * @return
	 * @throws
	 */
	public void setBranchLevel(final String indicatorAddrs,
			final String terminalId) {

		PwPortableActivity.getHandler().post(new Runnable() {
			public void run() {

				int maxBranch = 0;
				indicatorSDDBDao.startReadableDatabase(false);

				boolean isNull = false;
				// 判读是否有节点的分支编号为空
				String[] branchIndicators = indicatorAddrs.split("_");
				for (int i = 0; i < branchIndicators.length; i++) {
					String[] phaseIndicator = branchIndicators[i].split(",");

					for (int j = 1; j < phaseIndicator.length; j++) {
						List<Indicator> indicators = indicatorSDDBDao
								.queryList(
										"branch is null and terminalid=? and upper(indicatoraddr)=?",
										new String[] { terminalId,
												phaseIndicator[j].toUpperCase() });

						if (null != indicators && 0 < indicators.size()) {
							isNull = true;
							break;
						}
					}
				}

				if (isNull) { // 如果存在

					// 清空所有选中的分支编号
					for (int i = 0; i < branchIndicators.length; i++) {
						String[] phaseIndicator = branchIndicators[i]
								.split(",");

						for (int j = 1; j < phaseIndicator.length; j++) {
							indicatorSDDBDao
									.execSql(
											"update indicator set branch='' where upper(indicatoraddr)=?",
											new String[] { phaseIndicator[j]
													.toUpperCase() });
						}
					}

					// 查找最大的分支编号
					List<Map<String, String>> maps = indicatorSDDBDao
							.queryMapList(
									"select distinct max(branch) as maxbranch from indicator where terminalid=?",
									new String[] { terminalId });

					String maxBranchStr = maps.get(0).get("maxbranch");
					if (!StringUtil.isEmpty(maxBranchStr)) {
						maxBranch = Integer.parseInt(maxBranchStr);
					}

					// 修改各指示器的分支编号和级数
					for (int i = 0; i < branchIndicators.length; i++) {
						maxBranch++;

						String[] phaseIndicator = branchIndicators[i]
								.split(",");

						for (int j = 1; j < phaseIndicator.length; j++) {
							indicatorSDDBDao
									.execSql(
											"update indicator set branch=?,level=? where upper(indicatoraddr)=?",
											new String[] {
													maxBranch + "",
													j + "",
													phaseIndicator[j]
															.toUpperCase() });

						}
					}
				}

				indicatorSDDBDao.closeDatabase(false);
				webView.loadUrl("javascript:setBranchLevelCallback("
						+ maxBranch + ")");
			}
		});
	}

	/**
	 * 
	 * @Title: addOrModifyIndicator
	 * @Description: 新增/修改指示器
	 * @param
	 * @return
	 * @throws
	 */
	public void addOrModifyIndicator(final String jsonStr) {

		indicator = gson.fromJson(jsonStr, Indicator.class);
		indicator.setTime(DateTimeUtil.getCurrentDate());

		if (0 == indicator.get_id()) { // 为0，新增
			sqliteStorage.insertData(indicator, indicatorSDDBDao,
					new DataInsertListener() {

						public void onSuccess(long paramLong) {
							JSIHelper.showToast(context, "添加成功!");

							Map<String, Object> map = new HashMap<String, Object>();
							map.put("success", true);
							map.put("oper", "add");
							map.put("indicator", indicator);
							String result = gson.toJson(map);
							webView.loadUrl("javascript:editSuccessCallback("
									+ result + ")");
						}

						public void onFailure(int errorCode, String errorMessage) {
							JSIHelper.showToast(context, "添加失败!");
						}
					});
		} else { // 修改

			PwPortableActivity.getHandler().post(new Runnable() {

				public void run() {
					StringBuffer sqlBuffer = new StringBuffer();
					if (null != indicator) {
						sqlBuffer.append("update indicator ");

						boolean hasSet = false;
						String indicatorAddr = indicator.getIndicatoraddr();
						if (!StringUtil.isEmpty(indicatorAddr)) {
							sqlBuffer
									.append((!hasSet ? "set " : "")
											+ "indicatoraddr='" + indicatorAddr
											+ "', ");
							hasSet = true;
						}

						String phase = indicator.getPhase();
						if (!StringUtil.isEmpty(phase)) {
							sqlBuffer.append((!hasSet ? "set " : "")
									+ "phase='" + phase + "', ");
							hasSet = true;
						}

						String branch = indicator.getBranch();
						if (!StringUtil.isEmpty(branch) && !"0".equals(branch)) {
							sqlBuffer.append((!hasSet ? "set " : "")
									+ "branch='" + branch + "', ");
							hasSet = true;
						}

						int level = indicator.getLevel();
						if (0 != level && -1 != level) {
							sqlBuffer.append((!hasSet ? "set " : "")
									+ "level='" + level + "', ");
							hasSet = true;
						}

						String gpsx = indicator.getGpsx();
						sqlBuffer.append((!hasSet ? "set " : "") + "gpsx='"
								+ gpsx + "', ");
						hasSet = true;

						String gpsy = indicator.getGpsy();
						sqlBuffer.append((!hasSet ? "set " : "") + "gpsy='"
								+ gpsy + "', ");
						hasSet = true;

						String location = indicator.getLocation();
						sqlBuffer.append((!hasSet ? "set " : "") + "location='"
								+ location + "', ");
						hasSet = true;

						sqlBuffer.append((!hasSet ? "set " : "") + "time='"
								+ DateTimeUtil.getCurrentDate() + "' ");
						hasSet = true;
						sqlBuffer.append("where _id=" + indicator.get_id());

						if (hasSet) {
							indicatorSDDBDao.startReadableDatabase(false);
							indicatorSDDBDao.execSql(sqlBuffer.toString(), null);
							indicatorSDDBDao.closeDatabase(false);
						}

						JSIHelper.showToast(context, "修改成功!");

						Map<String, Object> map = new HashMap<String, Object>();
						map.put("success", true);
						map.put("oper", "modify");
						map.put("indicator", indicator);
						map.put("type", "indicator");
						String result = gson.toJson(map);
						webView.loadUrl("javascript:editSuccessCallback("
								+ result + ")");
					}
				}
			});
		}
	}

	/**
	 * 
	 * @Title: queryIndicatorById
	 * @Description: 根据Id获取指示器
	 * @param
	 * @return
	 * @throws
	 */
	public void queryIndicatorById(final String indicatorId) {

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("_id", indicatorId);

		sqliteStorage.findData(storageQuery, indicatorSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询指示器失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null != paramList && 0 < paramList.size()) {
							try {
								String jsonStr = gson.toJson(paramList.get(0));

								webView.loadUrl("javascript:queryIndicatorByIdCallback("
										+ jsonStr + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						}
					}
				});
	}

	/**
	 * 
	 * @Title: removeIndicator
	 * @Description: 删除指示器
	 * @param
	 * @return
	 * @throws
	 */
	public void removeIndicator(final String _id) {

		if (StringUtil.isEmpty(_id)) {
			JSIHelper.showToast(context, "指示器唯一标识不能为空!");
			return;
		}

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("schemeid", _id);

		sqliteStorage.findData(storageQuery, new WorkLineSDDBDao(context),
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "删除指示器失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null != paramList && 0 < paramList.size()) {
							JSIHelper.showToast(context, "指示器下存在电流数据, 不能删除!");
							webView.loadUrl("javascript:removePauseCallback()");
							return;
						}

						StorageQuery sq = new StorageQuery();
						sq.equals("_id", Integer.parseInt(_id));

						sqliteStorage.deleteData(sq, indicatorSDDBDao,
								new DataUpdateListener() {

									public void onSuccess(long paramLong) {
										JSIHelper.showToast(context, "删除成功!");

										SharedPreferences shared = context
												.getSharedPreferences(
														"startedIndicators", 0);
										shared.edit()
												.remove("indicator_" + _id)
												.commit();
										shared.edit()
												.remove("indicator_" + _id
														+ "_time").commit();

										Map<String, Object> map = new HashMap<String, Object>();
										map.put("success", true);
										map.put("indicatorId", _id);

										String result = gson.toJson(map);
										webView.loadUrl("javascript:removeSuccuessCallback("
												+ result + ")");
									}

									public void onFailure(int errorCode,
											String errorMessage) {
										JSIHelper.showToast(context, "删除失败!");
									}
								});
					}
				});

	}

	/**
	 * 
	 * @Title: getIndicator
	 * @Description: 获取指示器
	 * @param
	 * @return
	 * @throws
	 */
	public void getIndicator(final String _id) {

		PwPortableActivity.getHandler().post(new Runnable() {

			public void run() {

				indicatorSDDBDao.startReadableDatabase(false);
				Indicator indicator = indicatorSDDBDao.queryOne(Integer
						.parseInt(_id));
				indicatorSDDBDao.closeDatabase(false);

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("success", true);
				map.put("indicator", indicator);

				String result = gson.toJson(map);
				webView.loadUrl("javascript:getIndicatorCallback(" + result
						+ ")");
			}
		});
	}

	/**
	 * 
	 * @Title: modifyIndicatorAddr
	 * @Description: 修改指示器的通信地址
	 * @param
	 * @return
	 * @throws
	 */
	public void modifyIndicatorAddr(final String orgCommAddr,
			final String newCommAddr) {
		PwPortableActivity.getHandler().post(new Runnable() {
			public void run() {
				try {

					IndicatorSDDBDao indicatorSDDBDao = new IndicatorSDDBDao(
							context);
					indicatorSDDBDao.startReadableDatabase(false);
					indicatorSDDBDao
							.execSql(
									"update indicator set indicatoraddr=? where indicatoraddr=?",
									new String[] { newCommAddr.toUpperCase(),
											orgCommAddr.toUpperCase() });

					indicatorSDDBDao.closeDatabase(false);

					resultMap.clear();
					resultMap.put("success", true);
					resultMap.put("orgCommAddr", orgCommAddr);
					resultMap.put("newCommAddr", newCommAddr);
					String result = gson.toJson(resultMap);

					webView.loadUrl("javascript:modifyIndicatorAddrCallback("
							+ result + ")");
				} catch (Exception e) {
					JSIHelper.showToast(context, "修改指示器失败!");
				}
			}
		});
	}
}
